import * as path from "path"
import * as fs from "fs-extra"
import * as yaml from "js-yaml"
import IHelper from "./helper.service"
import { ClashService } from "@/modules/clash/clash.service"

export type ProxyGroup = {
  id: string
  port: number
  apiPort: number
  secret: string
  checkUrl: string
  fireCmd: string
  state: number
  proxies?: {key: string, delay: number}[]
}

class _IStore {
  appUrl: string = ""
  groups: ProxyGroup[] = [
    {id: "bili", port: 6001, apiPort: 6002, secret: "bilibili", checkUrl: "https://bilibili.com", fireCmd: "", state: 0, proxies: []},
    {id: "dy", port: 6003, apiPort: 6004, secret: "douyin", checkUrl: "https://douyin.com", fireCmd: "", state: 0},
    {id: "ks", port: 6005, apiPort: 6006, secret: "kuaishou", checkUrl: "https://kuaishou.com", fireCmd: "", state: 0},
  ]
  proxyKeys: string[] = []
  configFile: string = ""
  constructor() {
    this.initGroups()
  }

  initGroups() {
    this.groups = this.groups.map(item => {
      const binPath = path.join(process.cwd(), `bin/clash`)
      const itemConfigPath = path.join(process.cwd(), `bin/config.d/config_${item.id}.yaml`)
      fs.ensureFileSync(itemConfigPath)
      const content = ClashService.prepareClashConfig([], {port: item.port, secret: item.secret, apiPort: item.apiPort})
      const yamlString: string = yaml.dump(content, {noRefs: true})
      fs.writeFileSync(itemConfigPath, yamlString, "utf-8")
      return {
        ...item,
        fireCmd: `${binPath} -f ${itemConfigPath}`
      }
    })
  }
}

const IGlobal = new _IStore()

export default IGlobal